package com.pocket.demo.core.security.authorize;

import com.pocket.demo.base.consts.SecurityConst;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * 【demo-SpringSecurity-7.2】
 * 参考：https://blog.51cto.com/u_13250/9067842
 * @author zhaozhile
 */
//@Component
public class PockerAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for(ConfigAttribute attribute:configAttributes){
            if(SecurityConst.ROLE_NONE.equals(attribute.getAttribute())){
                // 判断用户是否已认证
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("");
                }else{
                    return ;
                }
            }
            // TODO 判断当前用户是否拥有访问当前资源的角色
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for(GrantedAuthority authority:authorities){
                if(authority.getAuthority().equals(attribute.getAttribute())){
                    return;   // 当前用户具备所需的角色, 无需判断
                }
            }
        }
        throw new AccessDeniedException("");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
